package com.tlb.web;

import java.util.*;
import java.text.*;
import javax.servlet.*;
import javax.naming.*;
import javax.servlet.http.*;
import javax.persistence.*;
import com.tlb.dto.*;
import com.tlb.ejb.*;
import java.sql.*;
import javax.sql.*;

public class Util {

    private static Util UTIL;
    public static int BLB = 0;
    public static int BCB = 1;
    private EntityManagerFactory emf;
    private static SimpleDateFormat postViewDateFormat = null;

    static {
        UTIL = new Util();
    }

    public static Util getUtil() {
        return UTIL;
    }

    private Util() {
        try {
            emf = Persistence.createEntityManagerFactory("BLB_PU");
        } catch (Exception e) {
            System.out.println("Exception initializing persistence factory: " + e.getMessage());
            e.printStackTrace();
        }
        postViewDateFormat = new SimpleDateFormat("MM/dd/yy hh:mm a");
    }

    public EntityManagerFactory getPersistenceFactory() {
        return emf;
    }

    public int getBoard(HttpServletRequest req) {
        if (req == null) {
            return BLB;
        }

        if (req.getHeader("x-forwarded-host") != null && req.getHeader("x-forwarded-host").trim().indexOf("bigcollegeboard.com") > -1) {
            return BCB;
        }

        return BLB;
    }

    public String getServerRoot(HttpServletRequest req) {
        if (req == null) {
            return "www.biglawboard.com";
        }

        if (req.getHeader("x-forwarded-host") != null) {
            if (req.getHeader("x-forwarded-host").trim().equalsIgnoreCase("www.bigcollegeboard.com")) {
                return "www.bigcollegeboard.com";
            } else {
                return "www.biglawboard.com";
            }
        }

        return "localhost:8080";
    }

    public SimpleDateFormat getPostViewDateFormat() {
        return postViewDateFormat;
    }

   
    
    public String getViewThreadAuthorString(PostView post) throws Exception {
        StringBuffer ret = new StringBuffer(70);
        ret.append("<span style='font-size: small'>Author:</span> <b>" + new MonikerDAO().fixHTML(post.getMonikerName()) + "</b>");
        if(post.getShowCounter())
            ret.append(" [" + post.getPostCount() + "]");
        
        if(post.getTagLine() != null && !post.getTagLine().equals(""))
            ret.append(" (<i>" + new MonikerDAO().fixHTML(post.getTagLine()) + "</i>)");        
        
        return ret.toString();
    }
    
    
    
    
    public Connection getRawConnection() throws Exception {
    	
    	
    	Context ctx = new InitialContext();
    	DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/tlbDS");
    	Connection conn = ds.getConnection();    	
    	
    	return conn;
    }
    
    
    
    
    
    
    
    
}
